package com.bluedon.ism.commons.dao;

import com.bluedon.ism.commons.entity.OperateAuth;
import com.bluedon.ism.commons.entity.Permission;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Repository(value="permissionDAO")
public class PermissionDAO extends BaseDAO {
	
	public Permission findById(Long id) {
		return (Permission) findObjectById(Permission.class, id);
	}
	
	public Permission getPermByOauthId(Long oauthId) {
	    String hql = "from Permission p where p.operateAuth.oauthId = " + oauthId;
	    return (Permission) uniqueElement(hql);
	}
	
	public Permission getPermByMenuId(Long menuId) {
	    String hql = "from Permission p where p.menu.mid = " + menuId;
	    return (Permission) uniqueElement(hql);
	}
	
	public OperateAuth getOperateAuthById(Long oauthId) {
	    return (OperateAuth) findObjectById(OperateAuth.class, oauthId);
	}
	
    public void updatePermission(Permission permission) {
        update(permission);
    }
    
    public void updateOauth(OperateAuth oauth) {
        update(oauth);
    }
	
	/**
	 * 得到所有菜单
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> getPermMenuListByMenuType(int menuType, boolean showCode) {
	    String sql = "select m.mid, m.title, m.href, m.parent_id, m.is_leaf, p.pid, p.PERMISSION_CODE from menu m" +
	            " join permission p on p.menu_id = m.mid where m.types  = " + menuType + " and p.perm_type = 0";
	    
	    List<Object[]> list = this.getSession().createSQLQuery(sql).list();
	    List<Map<String,Object>> treeList = new ArrayList<Map<String,Object>>();
	    for (Object[] obj : list) {
	        boolean isLeaf = Boolean.valueOf(obj[4].toString());
	        Map<String,Object> map = new HashMap<String,Object>();
	        map.put("id", obj[0]);
	        map.put("pId", obj[3]);
	        map.put("isParent", true); //子菜单下面总有权限关联
	        if (showCode) {
	            map.put("name", obj[1] + "[" + obj[6] + "]");
	        } else {
	            map.put("name", obj[1]);
            }
	        map.put("value", obj[5]);  //权限pid值
	        map.put("permType", 0); //菜单权限 0 操作权限 1
	        map.put("permCode", obj[6]); //权限编码
	        if (isLeaf) {
	            map.put("url", obj[2]);
	        }
	        treeList.add(map);
	    }
	    return treeList;
	}
	/**
	 * 得到所有PC菜单
	 * @return
	 */
	public List<Map<String,Object>> getPcPermMenuList(boolean showCode) {
	    return getPermMenuListByMenuType(0, showCode);
	}

	/**
	 * 得到所有授权操作
	 * @return
	 */
	public List<Map<String,Object>> getPermOauthListByMenuType(int menuType, boolean showCode) {
	    String sql = "select o.o_auth_id,o.o_auth_name,o.o_auth_code,o.o_auth_desc,o.menu_id, p.pid, p.PERMISSION_CODE from operate_auth o " +
	            " join permission p on o.o_auth_id = p.operate_auth_id where o.enabled = 1 and p.perm_type = 1 " +
	            " and o.menu_id in (select m.mid from menu m where m.types = " + menuType + ")";
	    
	    List<Object[]> list = this.getSession().createSQLQuery(sql).list();
	    List<Map<String,Object>> treeList = new ArrayList<Map<String,Object>>();
	    for (Object[] obj : list) {
	        Map<String,Object> map = new HashMap<String,Object>();
	        map.put("id", "o_" + obj[0]); // id值避免跟menu表的id重复加上前缀
	        map.put("pId", obj[4]);
	        map.put("isParent", false); //功能操作总是最底层
	        map.put("value", obj[5]);  //权限pid值
            if (showCode) {
                map.put("name", obj[1] + "[" + obj[6] + "]");
            } else {
                map.put("name", obj[1]);
            }
	        map.put("permType", 1); //菜单权限 0 操作权限 1
	        map.put("permCode", obj[6]); //权限编码
	        treeList.add(map);
	    }
	    return treeList;
	}
	/**
	 * 得到所有PC授权操作
	 * @return
	 */
	public List<Map<String,Object>> getPcPermOauthList(boolean showCode) {
	    return getPermOauthListByMenuType(0, showCode);
	}
	
	@SuppressWarnings("unchecked")
	public List<OperateAuth> getOperateAuthByMenu(long mid) {
		String hql = "from OperateAuth o where o.meuId = "+mid;
		return this.find(hql);
	}

	@SuppressWarnings("unchecked")
	public List<OperateAuth> getAllOperateAuth() {
		String hql = "from OperateAuth o ";
		return this.find(hql);
	}
	
	/**
	 * 添加指定角色权限
	 * @param rid
	 * @param permissionValues
	 * @return
	 */
	public int addRolePermissions(long rid,String permissionValues) {
		String sql = "insert into role_permission (rid,pid) select "+rid+",p.pid " +
				" from permission p where p.pid in (" + permissionValues + ")";
		int count = this.getSession().createSQLQuery(sql).executeUpdate();
		return count;
	}
	
	/**
	 * 删除指定角色指定权限
	 * @param rid
	 * @param permissionValues
	 * @return
	 */
	public int deleteRolePermissions(long rid,String permissionValues) {
		String sql = "delete from role_permission rp where rp.pid in ("+permissionValues+") and rp.rid = " + rid ;
		int count = this.getSession().createSQLQuery(sql).executeUpdate();
		return count;

	}
	/**
	 * 添加组织权限
	 * @param oid
	 * @param permissionValues
	 * @return
	 */
	public int addOrgPermissions(String oid,String permissionValues) {
	    String sql = "insert into role_org_permission (org_id,pid) select :oid , p.pid " +
	            " from permission p where p.pid in (" + permissionValues + ")";
	    int count = this.getSession().createSQLQuery(sql).setString("oid", oid).executeUpdate();
	    return count;
	}
	
	/**
	 * 删除组织可授权的权限 关联组织下的角色权限也要删除
	 * @param oid
	 * @param permissionValues
	 * @return
	 */
	public int deleteOrgPermissions(String oid,String permissionValues) {
	    String sql = "delete from role_org_permission rop where rop.pid in (" + permissionValues + ") and rop.org_id = :oid";
	    int count = this.getSession().createSQLQuery(sql).setString("oid", oid).executeUpdate();
	    if (count > 0) {
	        sql = "delete from role_permission rp where rp.rid in ( select r.rid from role r where r.org_id = :oid ) and rp.pid in (" + permissionValues + ")  ";
	        this.getSession().createSQLQuery(sql).setString("oid", oid).executeUpdate();
	    }
	    return count;
	}
	
	
	/**
	 * 查询指定角色拥有的权限pid，字段顺序rp.pid,rp.rid
	 * @param rid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getPermOfRole(long rid) {
		String sql = "select rp.pid,rp.rid from role_permission rp where rp.rid  = " + rid;
		return this.getSession().createSQLQuery(sql).list();
	}

	/**
	 * 查询指定角色拥有的权限pid，字段顺序pid,org_id
	 * @param oid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getPermOfOrg(String oid) {
	    String sql = "select pid,org_id from role_org_permission rop where rop.org_id  = :oid ";
	    return this.getSession().createSQLQuery(sql).setString("oid", oid).list();
	}
}
